//
//  Date.swift
//  WBCloud
//
//  Created by 李加建 on 2021/9/8.
//

import Foundation

public extension Date {
    func toString(dateFormat: String = "yyyy-MM-dd") -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "zh_CN")
        formatter.dateFormat = dateFormat
        let dateString = formatter.string(from: self)
        return dateString
    }

    func before(day: Int) -> Date {
        Date(timeInterval: TimeInterval(-86400 * day), since: self)
    }

    func after(day: Int) -> Date {
        Date(timeInterval: TimeInterval(86400 * day), since: self)
    }
}

public extension Date {
    static func creat(string: String, dateFormat: String) -> Date? {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "zh_CN")
        formatter.dateFormat = dateFormat
        return formatter.date(from: string)
    }
}

public extension Date {
    var year: Int? {
        let calender = Calendar.current
        let comp = calender.dateComponents([.year, .month, .day, .weekday], from: self)
        return comp.year
    }

    var month: Int? {
        let calender = Calendar.current
        let comp = calender.dateComponents([.year, .month, .day, .weekday], from: self)
        return comp.month
    }

    var day: Int? {
        let calender = Calendar.current
        let comp = calender.dateComponents([.year, .month, .day, .weekday], from: self)
        return comp.day
    }

    func getDaysInCurrentMonth() -> Int? {
        let calender = Calendar.current
        let comp = calender.dateComponents([.year, .month, .day], from: self)
        let year = comp.year ?? 0
        let month = comp.month ?? 0
        var startComps = DateComponents()
        startComps.day = 1
        startComps.month = month
        startComps.year = year

        var endComps = DateComponents()
        endComps.day = 1
        endComps.month = month == 12 ? 1 : month + 1
        endComps.year = month == 12 ? year + 1 : year
        let diff = calender.dateComponents([.day], from: startComps, to: endComps)

        return diff.day
    }
}
